package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.TaskCollectAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.TaskCollect;
import com.isunland.managesystem.entity.TaskCollectOriginal;
import com.isunland.managesystem.entity.WorkprocessFinish.FinishDtail;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@SuppressWarnings("deprecation") public class TaskCollectListFragment extends BaseListFragment {
  private static final int REQUEST_QUERY = 0;
  private TaskCollectAdapter mAdapter;
  private String mBegindate;
  private Date mEnddate;
  private String mjobNos;
  private String mStaffName;
  private TextView mNameTv;
  private TextView mStartDateTv;
  private TextView mEndDateTv;
  private int mPage = 1;// 请求第几页的数据.

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitleCustom(R.string.taskCollect);

    CurrentUser mCurrentUser = CurrentUser.newInstance(getActivity());
    String mMemberCode = mCurrentUser.getMemberCode();
    LogUtil.i("mMemberCode---===---===" + mMemberCode);

    mEnddate = new Date();
    mBegindate = MyDateUtil.dateToString(MyDateUtil.getBeforeOneMonth(), MyDateUtil.TYPE_DATE);
    mjobNos = mCurrentUser.getJobNumber();
    LogUtil.i("start=" + mBegindate + ",end=" + mEnddate + ",jobNo=" + mjobNos);

    mCurrentUser = CurrentUser.newInstance(getActivity());
    mStaffName = mCurrentUser.getRealName();
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    @SuppressWarnings("RestrictedApi") View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.header_sign, null, false);
    header.setOnClickListener(new OnClickListener() {

      @Override public void onClick(View v) {
        startQuery();
      }
    });
    mNameTv = (TextView) header.findViewById(R.id.tv_name_signHeader);
    mStartDateTv = (TextView) header.findViewById(R.id.tv_startDate_signHeader);
    mEndDateTv = (TextView) header.findViewById(R.id.tv_endDate_signHeader);
    updateHeader();
    mListview.addHeaderView(header);
    mPullRefreshListView.setMode(Mode.BOTH);
  }

  @Override public String getUrl() {

    return ApiConst.URL_TASK_COLLECT;
  }

  @Override public void resolveResponse(String json) {
    TaskCollectOriginal summary = new Gson().fromJson(json, TaskCollectOriginal.class);
    List<TaskCollect> summaryDetail = summary.getRows();
    if (summaryDetail != null && summaryDetail.size() == 0) {
      ToastUtil.show(R.string.that_is_all);
    }
    setAdapter(summaryDetail);
  }

  private void setAdapter(List<TaskCollect> summaryDetail) {

    if (summaryDetail == null) {
      summaryDetail = new ArrayList<>();
    }

    if (mAdapter == null) {
      mAdapter = new TaskCollectAdapter(getActivity(), summaryDetail);
      setListAdapter(mAdapter);
      return;
    }

    if (mPage == 1) {
      mAdapter.clear();
    }
    mAdapter.addAll(summaryDetail);
    ((TaskCollectAdapter) getListAdapter()).notifyDataSetChanged();
  }

  private void startQuery() {
    Intent intent = new Intent(getActivity(), AttendanceSummaryQueryActicity.class);
    if (!TextUtils.isEmpty(mStaffName)) {
      intent.putExtra(AttendanceSummaryQueryFragment.REQUEST_STAFF_NAME, mStaffName);
      intent.putExtra(AttendanceSummaryQueryFragment.REQUEST_JOB_NUMBER, mjobNos);
    }

    if (!TextUtils.isEmpty(mBegindate)) {
      intent.putExtra(AttendanceSummaryQueryFragment.REQUEST_BEGIN_DATE, mBegindate);
    }
    //		if (!TextUtils.isEmpty(mEnddate)) {
    intent.putExtra(AttendanceSummaryQueryFragment.REQUEST_END_DATE,
        MyDateUtil.dateToString(mEnddate, MyDateUtil.TYPE_DATE));
    //		}
    intent.putExtra(AttendanceSummaryQueryFragment.VALUE_FROM,
        AttendanceSummaryQueryFragment.TASK_COLLECT);
    startActivityForResult(intent, REQUEST_QUERY);
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();
    Date startDate = MyDateUtil.stringToDate(mBegindate, MyDateUtil.TYPE_DATE);
    params.put("page", mPage + "");
    params.put("pageSize", "20");
    params.put("beginPlanStagecompleteTime", startDate == null ? "" : startDate.getTime() + "");
    params.put("endPlanStagecompleteTime", mEnddate.getTime() + "");
    params.put("jobNo", mjobNos);

    // params.put("begindate", mBegindate);
    // params.put("enddate", mEnddate);
    //
    // params.put("isPage", "0");
    //
    // params.put("memberCode", mMemberCode);
    // params.put("orderField", "jobno");
    // params.put("orderSeq", "asc, date asc");
    return params;
  }

  private void updateHeader() {
    mStartDateTv.setText(mBegindate);
    mEndDateTv.setText(MyDateUtil.parseTimeToString(mEnddate, MyDateUtil.TYPE_DATE));
    mNameTv.setText(
        MyStringUtil.isEmpty(mStaffName) ? getString(R.string.pleaseSelect) : mStaffName);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_query, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  /**
   * 响应ActionBar中的按钮
   */
  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      // 响应返回按钮

      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;

      case R.id.menu_item_query:
        startQuery();
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }

    if (requestCode == REQUEST_QUERY && data != null) {
      mjobNos = data.getStringExtra(AttendanceSummaryQueryFragment.REQUEST_JOB_NUMBER);
      mBegindate = data.getStringExtra(AttendanceSummaryQueryFragment.REQUEST_BEGIN_DATE);
      String endTime = data.getStringExtra(AttendanceSummaryQueryFragment.REQUEST_END_DATE);
      //结束时间范围要是当天结束.
      endTime = endTime + " 23:59:59";
      mEnddate = MyDateUtil.stringToDate(endTime, MyDateUtil.TYPE_ALL);
      mStaffName = data.getStringExtra(AttendanceSummaryQueryFragment.REQUEST_STAFF_NAME);
      updateHeader();
    }
    mPullRefreshListView.setMode(Mode.PULL_FROM_START);
    mPage = 1;
    volleyPost();
    mPullRefreshListView.setMode(Mode.BOTH);
    super.onActivityResult(requestCode, resultCode, data);
  }

  @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) {

    Mode mode = refreshView.getCurrentMode();
    if (mode.equals(Mode.PULL_FROM_START)) {

      mPage = 1;
    }
    if (mode.equals(Mode.PULL_FROM_END)) {
      mPage++;
    }
    volleyPost();
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    //		FinishDtail detail = mAdapter.getItem(position - 1);
    if (position < 2) return;
    TaskCollect item = mAdapter.getItem(position - 2);
    if (item == null) return;
    FinishDtail detail = item.turn();
    Intent intent = new Intent(getActivity(), WorkProcessFinishDetailActicity.class);
    intent.putExtra(WorkProcessFinishDetailFragment.EXTRA_VALUE, detail);
    intent.putExtra(WorkProcessFinishDetailFragment.EXTRA_FROM,
        WorkProcessFinishDetailFragment.VALUE_TASK_COLLECT);
    startActivity(intent);
    super.onListItemClick(l, v, position, id);
  }
}
